import { Form, Input, Radio } from 'antd';
import { ModelerService } from '@/pages/workflow/model/components/modeler/ModelerService';
import { useEffect, useState } from 'react';
import { GSelect } from 'geminis-react';

export const ActiveForm = (props: { modelerService: ModelerService }) => {
  const [form] = Form.useForm();
  const [type, setType] = useState('gemini');

  const updateValue = () => {
    const value = form.getFieldsValue();
    setType(value.formType);
    props.modelerService.setProperty(
      'flowable:formKey',
      value.formType === 'gemini'
        ? '/everydata-pc/everydata/form/view?id=' + value.formKey
        : value.formUrl,
    );
  };

  useEffect(() => {
    const url = props.modelerService?.businessObject.$attrs['flowable:formKey'];
    if (url) {
      const start = url.indexOf('/everydata-pc/everydata/form/view?id=');
      const configType = start === 0 ? 'gemini' : 'other';
      setType(configType);
      let key = null;

      if (configType === 'gemini') {
        key = url.substring(37);
      }

      form.setFieldsValue({
        formType: configType,
        formUrl: url,
        formKey: key,
      });
    }
  }, [props.modelerService.element]);

  return (
    <Form layout="vertical" form={form}>
      <Form.Item label="来源" name="formType">
        <Radio.Group onChange={updateValue} value={type}>
          <Radio value="gemini">内置</Radio>
          <Radio value="other">外部</Radio>
        </Radio.Group>
      </Form.Item>
      <Form.Item label="表单地址" name="formUrl" hidden={type === 'gemini'}>
        <Input.TextArea rows={8} onBlur={updateValue} />
      </Form.Item>
      <Form.Item label="表单" name="formKey" hidden={type !== 'gemini'}>
        <GSelect
          url="/api/everydata/forms"
          method="post"
          onChange={updateValue}
        />
      </Form.Item>
    </Form>
  );
};
